/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package br.com.foxline.manager.search;

import br.com.foxline.enums.PartQuality;
import br.com.foxline.enums.TypeDocument;
import br.com.foxline.enums.TypeTitleDocument;
import br.com.foxline.model.*;
import br.com.foxline.service.*;
import br.com.foxline.util.ConverterImg;
import br.com.foxline.util.Msg;
import java.io.IOException;
import java.io.InputStream;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import javax.annotation.PostConstruct;
import javax.ejb.EJB;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ViewScoped;
import javax.faces.context.FacesContext;
import javax.faces.model.SelectItem;
import org.primefaces.event.FileUploadEvent;

/**
 *
 * @author roniere
 */
@ManagedBean
@ViewScoped
public class ManagerSearchTitleDocument  implements Serializable{
    
    @EJB
    StampService stampService;
    @EJB
    PeopleService peopleService;
    @EJB
    QualityService qualityService;
    @EJB
    TypeStampService typeStampService;
    @EJB
    TitleDocumentService titleDocumentService;
    
    @EJB
    AnnexService annexService;
    
    private TitleDocument titleDocument;
    private TitleDocument titleDocumentShow;
    private TitleDocument titleDocumentEdit;
    
    private People people;
    private People peopleEdit;
    
    private Part part;
    private Part partEdit;
    private List<Part> parts;
    
    private Stamp stamp;
    private Stamp stampEdit;
    private List<Stamp> stamps;
    
    private TypeStamp typeStampObj;
    
    private Annex annex;
    private List<Annex> annexs;
    private List<Annex> lstAnnex;
    
    private String tdEdit;
    private String tdShow;
    
    private List<TitleDocument> titleDocuments;
    
    private Annex annexToRemove;

    @PostConstruct
    public void init() {
        
        titleDocument = new TitleDocument();
        lstAnnex = new ArrayList<Annex>();
        people = new People();
        people.setTipoDocumento(TypeDocument.CPF);
        
        part = new Part();
        parts = new ArrayList<Part>();
        stamp = new Stamp();
        stamps = new ArrayList<Stamp>();

        typeStampObj = new TypeStamp();
        annexs = new ArrayList<Annex>();

        Map<String, String> params = FacesContext.getCurrentInstance().getExternalContext().getRequestParameterMap();
        tdEdit = params.get("tdEdit");
        tdShow = params.get("tdShow");
        paramPost();
    }
    
    public void paramPost() {
        try {
            if (tdShow != null) {
                titleDocumentShow = titleDocumentService.find(Long.parseLong(tdShow));
                if (titleDocumentShow != null) {
                    titleDocumentShow.setAnnex(annexService.getAnnexByTitleDocument(titleDocumentShow));
                }
            } else if (tdEdit != null) {
                peopleEdit = new People();
                peopleEdit.setTipoDocumento(TypeDocument.CPF);
                partEdit = new Part();
                stampEdit = new Stamp();
                titleDocumentEdit = titleDocumentService.find(Long.parseLong(tdEdit));
                if (tdEdit != null) {
                    titleDocumentEdit.setAnnex(annexService.getAnnexByTitleDocument(titleDocumentEdit));
                }
                
                
            } 
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public Annex getAnnex() {
        return annex;
    }

    public void setAnnex(Annex annex) {
        this.annex = annex;
    }

    public List<Annex> getAnnexs() {
        return annexs;
    }

    public void setAnnexs(List<Annex> annexs) {
        this.annexs = annexs;
    }

    public Part getPart() {
        return part;
    }

    public void setPart(Part part) {
        this.part = part;
    }

    public List<Part> getParts() {
        return parts;
    }

    public void setParts(List<Part> parts) {
        this.parts = parts;
    }

    public People getPeople() {
        return people;
    }

    public void setPeople(People people) {
        this.people = people;
    }

    public PeopleService getPeopleService() {
        return peopleService;
    }

    public void setPeopleService(PeopleService peopleService) {
        this.peopleService = peopleService;
    }

    public QualityService getQualityService() {
        return qualityService;
    }

    public void setQualityService(QualityService qualityService) {
        this.qualityService = qualityService;
    }

    public Stamp getStamp() {
        return stamp;
    }

    public void setStamp(Stamp stamp) {
        this.stamp = stamp;
    }

    public StampService getStampService() {
        return stampService;
    }

    public void setStampService(StampService stampService) {
        this.stampService = stampService;
    }

    public List<Stamp> getStamps() {
        return stamps;
    }

    public void setStamps(List<Stamp> stamps) {
        this.stamps = stamps;
    }

    public TitleDocument getTitleDocument() {
        return titleDocument;
    }

    public void setTitleDocument(TitleDocument titleDocument) {
        this.titleDocument = titleDocument;
    }

    public TypeStamp getTypeStampObj() {
        return typeStampObj;
    }

    public void setTypeStampObj(TypeStamp typeStampObj) {
        this.typeStampObj = typeStampObj;
    }

    public TypeStampService getTypeStampService() {
        return typeStampService;
    }

    public void setTypeStampService(TypeStampService typeStampService) {
        this.typeStampService = typeStampService;
    }

    public List<Annex> getLstAnnex() {
        return lstAnnex;
    }

    public void setLstAnnex(List<Annex> lstAnnex) {
        this.lstAnnex = lstAnnex;
    }

    public Part getPartEdit() {
        return partEdit;
    }

    public void setPartEdit(Part partEdit) {
        this.partEdit = partEdit;
    }

    public People getPeopleEdit() {
        return peopleEdit;
    }

    public void setPeopleEdit(People peopleEdit) {
        this.peopleEdit = peopleEdit;
    }

    public Stamp getStampEdit() {
        return stampEdit;
    }

    public void setStampEdit(Stamp stampEdit) {
        this.stampEdit = stampEdit;
    }

    public String getTdEdit() {
        return tdEdit;
    }

    public void setTdEdit(String tdEdit) {
        this.tdEdit = tdEdit;
    }

    public String getTdShow() {
        return tdShow;
    }

    public void setTdShow(String tdShow) {
        this.tdShow = tdShow;
    }

    public List<TitleDocument> getTitleDocuments() {
        return titleDocuments;
    }

    public void setTitleDocuments(List<TitleDocument> titleDocuments) {
        this.titleDocuments = titleDocuments;
    }

    public Annex getAnnexToRemove() {
        return annexToRemove;
    }

    public void setAnnexToRemove(Annex annexToRemove) {
        this.annexToRemove = annexToRemove;
    }

    public TitleDocument getTitleDocumentEdit() {
        return titleDocumentEdit;
    }

    public void setTitleDocumentEdit(TitleDocument titleDocumentEdit) {
        this.titleDocumentEdit = titleDocumentEdit;
    }

    public TitleDocument getTitleDocumentShow() {
        return titleDocumentShow;
    }

    public void setTitleDocumentShow(TitleDocument titleDocumentShow) {
        this.titleDocumentShow = titleDocumentShow;
    }
    
    

    public List<SelectItem> typeTitleDocumentList() {
        List<SelectItem> items = new ArrayList<SelectItem>();
        for (TypeTitleDocument tipo : TypeTitleDocument.values()) {
                items.add(new SelectItem(tipo, tipo.getName()));
        }
        return items;
    }
    
    public void addPartsEdit() {

        if (peopleEdit.getName().isEmpty() || peopleEdit.getName() == null) {
            Msg.messagemError("O nome da parte é obrigatório");
            return;
        }

        if (partEdit.getPartQuality() != null) {
            partEdit.setPartQuality(qualityService.find(partEdit.getPartQuality().getId()));
        }

        partEdit.setPeople(peopleEdit);
        titleDocumentEdit.getParts().add(partEdit);

        peopleEdit = new People();
        peopleEdit.setTipoDocumento(TypeDocument.CPF);
        partEdit = new Part();

    }

    public void addStampsEdit() {
        stampEdit.setTypeStamp(typeStampService.find(typeStampObj.getId()));
        
        if(titleDocumentEdit.getStamp() != null && !titleDocumentEdit.getStamp().isEmpty()){
            titleDocumentEdit.getStamp().add(stampEdit);
        }else{
            List<Stamp> lsrt = new ArrayList<Stamp>();
            lsrt.add(stampEdit);
            titleDocumentEdit.setStamp(lsrt);
        }
        stampEdit = new Stamp();
    }
    
    public void addParts() {

        if (people.getName().isEmpty() || people.getName() == null) {
            Msg.messagemError("O nome da parte é obrigatório");
            return;
        }

        if (part.getPartQuality() != null) {
            part.setPartQuality(qualityService.find(part.getPartQuality().getId()));
        }

        part.setPeople(people);
        parts.add(part);
        people = new People();
        people.setTipoDocumento(TypeDocument.CPF);
        part = new Part();

    }
    
    public void remove(TitleDocument c){
        try{
        titleDocumentService.delete(c);
        titleDocuments.remove(c);
        Msg.messagemInfo("Excluído com Sucesso");
        }catch(Exception e){
            e.printStackTrace();
        }
    }

    public void removePart(int p) {
        titleDocumentEdit.getParts().remove(p);
    }
    public void removeStamp(int p) {
        titleDocumentEdit.getStamp().remove(p);
    }
    
    public void addStamps() {
        stamp.setTypeStamp(typeStampService.find(typeStampObj.getId()));
        stamps.add(stamp);
        stamp = new Stamp();
    }
    
    public void removeAnnexAux(Annex p) {
        annexToRemove = p;
    }
    
    public void removeAnnex() {
        if(annexToRemove!= null){
            titleDocumentEdit.getAnnex().remove(annexToRemove);
        }
    }

    public void edit() {
        titleDocumentEdit.setAnnex(lstAnnex);
        titleDocumentService.update(titleDocumentEdit);
        Msg.messagemInfo("Atualizado com Sucesso !");
        titleDocumentEdit = titleDocumentService.find(titleDocumentEdit.getId());
        titleDocumentEdit.setAnnex(annexService.getAnnexByTitleDocument(titleDocumentEdit));
    }
    
    public void handle(FileUploadEvent event) throws IOException {
        handleAux(event.getFile().getContents(), event.getFile().getFileName(),
                event.getFile().getContentType(), event.getFile().getInputstream());
    }

      private void handleAux(byte[] imageBytes, String nome, String tipo, InputStream is) throws IOException {

        byte[] bytes = null;
        
        Annex annex = new Annex();
        if (tipo.equalsIgnoreCase("image/tiff")) {
            bytes = ConverterImg.convertTiffToJpg(is);
            annex.setType("jpeg");
            annex.setDescription(nome.replaceAll("tif|tiff", "jpeg"));
        } else {
            bytes = imageBytes;
            annex.setType(tipo);
            annex.setDescription(nome);
        }
        if (bytes != null) {
            annex.setFileByte(bytes);
            titleDocumentEdit.getAnnex().add(annex);
            //lstAnnex.add(annex);
            System.err.println("Annexoo..." + lstAnnex.size());
            annex = new Annex();
            Msg.messagemWarn("Anexado");
        }

    }

     public void ajaxVerifyPeopleExist() {
        String doc = "";
        if (peopleEdit.getTipoDocumento() == TypeDocument.CNPJ) {
            doc = peopleEdit.getCnpj();
        } else if (peopleEdit.getTipoDocumento() == TypeDocument.CPF) {
            doc = peopleEdit.getCpf();
        } else if (peopleEdit.getTipoDocumento() == TypeDocument.OAB) {
            doc = peopleEdit.getOAB();
        }
        if(doc ==null || doc.isEmpty())
            return;
        People pe = peopleService.existPeople(peopleEdit.getTipoDocumento(), doc);
        if (pe != null) {
            peopleEdit = pe;
        }
    }

    public List<SelectItem> typeDocumentList() {
        List<SelectItem> items = new ArrayList<SelectItem>();
        for (TypeDocument tipo : TypeDocument.values()) {
            if (tipo != TypeDocument.OAB) {
                items.add(new SelectItem(tipo.getType(), tipo.getName()));
            }
        }
        return items;
    }

    public List<SelectItem> partQualitytList() {
        List<SelectItem> items = new ArrayList<SelectItem>();
        for (PartQuality tipo : PartQuality.values()) {
            items.add(new SelectItem(tipo));
        }
        return items;
    }
    
     public List<Quality> autocompleteQuality(String str) {
        return qualityService.autoComplete(str);
    }
     
    public void create() {
        System.err.println("CRIANDO TITULO E DOCUMENTOS");
        
        titleDocument.setAnnex(annexs);
        titleDocument.setStamp(stamps);
        People person = null;
        for (Part p : parts) {
            if (p.getPeople().getId() == null) {
                peopleService.save(p.getPeople());
            } else {
                peopleService.update(p.getPeople());
            }

        }
        titleDocument.setDatetcad(new Date());
        titleDocument.setParts(parts);
        titleDocumentService.save(titleDocument);
        init();

    }
    public void update() {
        System.err.println("ATUALIZANDO TITULO E DOCUMENTOS");
        People person = null;
        for (Part p : titleDocumentEdit.getParts()) {
            if (p.getPeople().getId() == null) {
                peopleService.save(p.getPeople());
            } else {
                peopleService.update(p.getPeople());
            }

        }
        titleDocumentService.update(titleDocumentEdit);
        Msg.messagemInfo("Atualizado com Sucesso");
        init();
    }
      
    public void search() {
        part.setPeople(people);
        titleDocuments = titleDocumentService.searchTitleDocument(titleDocument, part, stamp);
        //PESQUISA
    }
    
    
    
}
